package eu.akka.labs.jms.server.services;

import javax.ejb.Local;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.apache.log4j.Logger;

import eu.akka.labs.jms.common.JmsMessageProducer;
import eu.akka.labs.jms.common.MyEntity;

@Local
@Stateless
@WebService(targetNamespace = "http://services.labs.jee.com/v1/", name = "JobManager", portName = "JobManagerServicePort", serviceName = "JobManagerService")
@SOAPBinding(style = SOAPBinding.Style.DOCUMENT, use = SOAPBinding.Use.LITERAL, parameterStyle = SOAPBinding.ParameterStyle.WRAPPED)
public class JobManagerService implements IJobManagerService {

	private static final Logger log = Logger.getLogger(JobManagerService.class);

	@PersistenceContext
	EntityManager em;

	@WebMethod
	@Override
	public void manageMessage(@WebParam(name = "message") String message) {
		log.info("Message : " + message + " recu.");

		// Creation d'une entitee
		MyEntity entity = new MyEntity();
		entity.setMessage(message);
		entity.setCpt(1);

		// Persistence de l'entitee
		em.persist(entity);

		// Envoi d'un message JMS
		log.info("Send JMS message for entity :" + entity);
		JmsMessageProducer jmsProd = new JmsMessageProducer();
		jmsProd.sendJmsObjectMessage(entity.getId());
	}

	@WebMethod
	@Override
	public void manageWithSubTransactionMessage(@WebParam(name = "message") String message) {
		log.info("Message :" + message + "recu.");

		MyEntity entity = doSubTransaction(message);

		// Envoi d'un message JMS
		log.info("Send JMS message for entity :" + entity);
		JmsMessageProducer jmsProd = new JmsMessageProducer();
		jmsProd.sendJmsObjectMessage(entity.getId());
	}

	@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
	private MyEntity doSubTransaction(String message) {

		// Creation d'une entitee
		MyEntity entity = new MyEntity();
		entity.setMessage(message);
		entity.setCpt(1);

		// Persistence de l'entitee
		em.persist(entity);

		return entity;
	}
}